package Task3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class MultiThread extends Thread {
    private Socket accept;
    public MultiThread(Socket accept){
        this.accept = accept;
    }
    @Override
    public void run(){

        BufferedReader bf = null;
        PrintStream ps = null;

        try {
            bf = new BufferedReader(new InputStreamReader(accept.getInputStream()));
            ps = new PrintStream(accept.getOutputStream());
            while(true) {
                //3. 使用输入输出流进行通讯 -->对客户端发送的字符串进行接收并打印
                String read = bf.readLine();
                InetAddress inetAddress = accept.getInetAddress();
                System.out.println("客户端" +inetAddress + "发来的字符串是:" + read);
                //4. 服务器向客户端回发消息
                ps.println("收到客户端" + inetAddress + "发来的消息:" + read);
                System.out.println("服务器回发数据成功！");
                if(read.equals("结束通讯")){
                    System.out.println("客户端" + inetAddress + "结束通讯！");

                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4. 关闭Socket通讯并释放相关资源
            try {
                if(ps != null){
                    ps.close();
                }
                if(bf != null){
                    bf.close();
                }
                if(accept != null){
                    accept.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
